package com.cart.controller;

import com.cart.models.Admin;
import com.cart.models.Customer;
import com.cart.pojo.OrderHistory;
import com.cart.pojo.Product;
import com.cart.services.OrderHistoryRepository;
import com.cart.services.ProductRepository;
import com.cart.services.UserRepository;

import java.util.List;
import java.util.Scanner;

public class CustomerActionsController {

    private static int loginAttempts = 0;
    private static final int MAX_LOGIN_ATTEMPTS = 5;
    private static boolean isLocked = false;

    public static Boolean customerActions(Customer customer, UserRepository userRepository, ProductRepository productRepository, OrderHistoryRepository orderHistoryRepository, Scanner scanner) {
        while (true) {
            System.out.println("\n客户操作菜单：");
            System.out.println("1. 浏览商品");
            System.out.println("2. 加入购物车");
            System.out.println("3. 查看购物车");
            System.out.println("4. 修改购物车");
            System.out.println("5. 结账");
            System.out.println("6. 查看购买历史");
            System.out.println("7. 修改密码");
            System.out.println("8. 忘记密码");
            System.out.println("9. 退出");
            System.out.print("请选择操作: ");
            int choice = scanner.nextInt();
            scanner.nextLine();  // 清理换行符

            switch (choice) {
                case 1:
                    browseProducts(productRepository);
                    break;
                case 2:
                    addToCart(customer, productRepository, scanner);
                    break;
                case 3:
                    viewCart(customer);
                    break;
                case 4:
                    modifyCart(customer, scanner);
                    break;
                case 5:
                    checkout(customer, productRepository, orderHistoryRepository);
                    break;
                case 6:
                    viewOrderHistory(customer, orderHistoryRepository);
                    break;
                case 7:
                    Boolean res = changePassword(customer, userRepository, scanner);
                    if (res) return res;
                    break;
                case 8:
                    forgotPassword(scanner);
                    break;
                case 9:
                    System.out.println("退出客户操作");
                    return false;
                default:
                    System.out.println("无效选择，请重试。");
            }
        }
    }

    // 1. 浏览商品
    private static void browseProducts(ProductRepository productRepository) {
        System.out.println("\n商品列表：");
        productRepository.findAll().forEach(product -> {
            System.out.println("商品ID: " + product.getId() + " 名称: " + product.getName() + " - 价格: " + product.getRetailPrice());
        });
    }

    // 2. 加入购物车
    private static void addToCart(Customer customer, ProductRepository productRepository, Scanner scanner) {
        System.out.print("请输入商品ID: ");
        int productId = scanner.nextInt();
        System.out.print("请输入购买数量: ");
        int quantity = scanner.nextInt();
        scanner.nextLine();

        Product product = productRepository.findById(productId);
        if (product != null) {
            customer.addToCart(productRepository, productId, quantity);
            System.out.println("商品已加入购物车！");
        } else {
            System.out.println("商品不存在！");
        }
    }

    // 3. 查看购物车
    private static void viewCart(Customer customer) {
        System.out.println("\n您的购物车：");
        if (customer.getCart().getItems().isEmpty()) {
            System.out.println("购物车为空！");
        } else {
            customer.getCart().getItems().forEach(item -> {
                System.out.println("商品: " + item.getProduct().getName() + " - 数量: " + item.getQuantity() + " - 小计: " + (item.getProduct().getRetailPrice() * item.getQuantity()));
            });
        }
    }

    // 4. 修改购物车
    private static void modifyCart(Customer customer, Scanner scanner) {
        System.out.print("请输入要修改的商品ID: ");
        int productId = scanner.nextInt();
        System.out.print("请输入新的数量（输入0以移除商品）: ");
        int quantity = scanner.nextInt();
        scanner.nextLine();

        if (quantity == 0) {
            customer.removeFromCart(productId);
            System.out.println("商品已从购物车移除！");
        } else {
            customer.updateCart(productId, quantity);
            System.out.println("购物车商品数量已更新！");
        }
    }

    // 5. 结账
    private static void checkout(Customer customer, ProductRepository productRepository, OrderHistoryRepository orderHistoryRepository) {
        System.out.println("\n结账中...");
        if (customer.getCart().getItems().isEmpty()) {
            System.out.println("购物车为空，无法结账！");
            return;
        }

        // 模拟支付流程
        customer.checkout(productRepository);
        System.out.println("结账成功！");

        // 保存订单历史
        OrderHistory orderHistory = new OrderHistory(customer.getId(), customer.getCart().getItems(), new java.util.Date());
        orderHistoryRepository.saveOrder(orderHistory);
        System.out.println("订单已保存到购买历史。");

        // 清空购物车
        customer.clearCart();
    }

    // 6. 查看购买历史
    private static void viewOrderHistory(Customer customer, OrderHistoryRepository orderHistoryRepository) {
        System.out.println("\n购买历史：");
        List<OrderHistory> orders = orderHistoryRepository.findByUserId(customer.getId());
        if (orders.isEmpty()) {
            System.out.println("没有购买历史。");
        } else {
            for (OrderHistory order : orders) {
                System.out.println("订单时间: " + order.getPurchaseDate());
                order.getItems().forEach(item -> {
                    System.out.println("商品: " + item.getProduct().getName() + " - 数量: " + item.getQuantity() + " - 小计: " + (item.getProduct().getRetailPrice() * item.getQuantity()));
                });
            }
        }
    }

    // 7. 修改密码
    private static Boolean changePassword(Customer customer, UserRepository userRepository, Scanner scanner) {
        System.out.print("请输入新密码（大于8个字符，必须包含大小写字母、数字和符号）: ");
        String newPassword = scanner.nextLine();

        if (isValidPassword(newPassword)) {
            userRepository.updatePassword(customer.getId(), Admin.md5Hash(newPassword));
            System.out.println("密码修改成功！");
            return true;
        } else {
            System.out.println("密码格式不正确！");
            return false;
        }
    }

    // 8. 忘记密码
    private static void forgotPassword(Scanner scanner) {
        System.out.print("请输入您的用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入您注册的邮箱: ");
        String email = scanner.nextLine();

        // 模拟发送新密码
        String newPassword = generateRandomPassword();
        System.out.println("系统已发送新的密码到您的邮箱: " + email);
        System.out.println("新密码: " + newPassword);
        // 在实际应用中，这里应调用重置密码的逻辑
    }

    // 密码验证
    private static boolean isValidPassword(String password) {
        if (password.length() < 8) return false;
        boolean hasUpper = false, hasLower = false, hasDigit = false, hasSpecial = false;
        for (char c : password.toCharArray()) {
            if (Character.isUpperCase(c)) hasUpper = true;
            if (Character.isLowerCase(c)) hasLower = true;
            if (Character.isDigit(c)) hasDigit = true;
            if (!Character.isLetterOrDigit(c)) hasSpecial = true;
        }
        return hasUpper && hasLower && hasDigit && hasSpecial;
    }

    // 随机生成密码
    private static String generateRandomPassword() {
        return "Abc@12345";  // 模拟生成的密码，在实际应用中应该生成随机的密码
    }
}
